'use client'
import {useEffect, useState} from 'react';
import {useParams, useRouter} from 'next/navigation';
import {Movie} from "@/app/types";
import {NextResponse} from "next/server";

import {useToast} from "@/components/ui/use-toast"

import {Button} from "@/components/ui/button"

import Rating from '@/components/Rating';

const MovieDetails = () => {
    const router = useRouter()
    const [movie,setMovie ] = useState<Movie | null>(null);
    const [rating, setRating] = useState<number>(0);
    const [averageRating, setAverageRating] = useState<number>(0);
    const {toast} = useToast()

    const {id} = useParams();

    const handleRating = (newRating: any) => {
        setRating(newRating);
    };

    useEffect(() => {
        const fetchMovie = async () => {
            if (id) {
                const response = await fetch(`/api/movies/getById/${id}`);
                const data = await response.json();
                setMovie(data);
                setAverageRating(data.averageRating)
            }
        };
        fetchMovie();
    }, [id]);

    const handleRatingSubmit = async () => {
        const response = await fetch(`/api/movies/rating/${id}`, {
            method: 'POST',
            body: `${rating}`,
            headers: {'Content-Type': 'application/json'},
        });

        if (!response.ok) {
            toast({
                title: "Rate Fail,please rate the movie later",
                duration: 1000
            })
            return NextResponse.json({error: 'Rating fail'}, {status: response.status});

        } else {
            const responseData = await response.json();
            setAverageRating(responseData.averageRating)

            toast({
                title: "Rate success",
                duration: 1000
            })
            return responseData;
        }
    };

    if (!movie) return <div>Loading...</div>;

    return (
        <div className="container mx-auto p-4">
            <div className="flex flex-row-reverse pr-20">
                <Button onClick={() => router.push('/')} className=" bg-blue-500  rounded">
                    Back
                </Button>
            </div>

            <h2 className="text-2xl font-bold">{movie.title}</h2>
            <p>Genres: {movie.genres.map(e => e + " ")}</p>
            <p>Release Date: {movie.year}</p>
            <p className="mb-3">Average Rating: {averageRating ? averageRating.toFixed(2) : ''}</p>
            <div className="flex flex-row flex-row-reverse pr-20">
                <Button onClick={handleRatingSubmit} className="bg-blue-500 text-white px-4 py-2 rounded">
                    Submit Rating
                </Button>
                <label className=" block  mr-5"><Rating onRating={handleRating}/></label>

            </div>

            <img src={movie.posterUrl} alt={movie.title} className="w-full h-auto mt-2"/>
        </div>
    );
};

export default MovieDetails
